﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;

using OpenGL4NET;

namespace WSTest
{
	static class Program
	{
		[DllImport("glu32.dll", EntryPoint="gluPerspective")]
		public static extern void gluPerspective(double fovy, double aspect, double zNear, double zFar);
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main()
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);

			var form = new Form1();
			form.HandleCreated += (o, e) => 
			{ 
				InitOpenGL(form);
				form.MyInit();
			};
			Application.Run(form);
		}

		public static uint ID;

		static void InitOpenGL(Form form)
		{
			try
			{
				IntPtr hdc = Windows.GetDC(form.Handle);
				PixelFormatDescriptor pfd = new PixelFormatDescriptor();
				pfd.Flags = PFD.FLAGS.DOUBLEBUFFER | PFD.FLAGS.SUPPORT_OPENGL | PFD.FLAGS.DRAW_TO_WINDOW;
				pfd.PixelType = PFD.PIXEL_TYPE.RGBA;
				pfd.ColorBits = 32;
				pfd.AlphaBits = 8;
				pfd.DepthBits = 24;
				pfd.StencilBits = 8;
				pfd.LayerType = PFD.LAYER_TYPE.MAIN_PLANE;

				int pixel = wgl.ChoosePixelFormat(hdc, pfd);
				wgl.SetPixelFormat(hdc, pixel, pfd); 
				
				var hrc = wgl.CreateContext(hdc);
				wgl.MakeCurrent(hdc, hrc);

				Loader.Load(typeof(gl));
				Loader.Load(typeof(wgl));

				gl.ClearColor(0, 0, 0, 0);
				gl.ClearDepth(1.0f);
				gl.Enable(GL.DEPTH_TEST);
				gl.Enable(GL.TEXTURE_2D);
				gl.Hint(GL.PERSPECTIVE_CORRECTION_HINT, GL.NICEST);

				ID = gl.CreateProgram();

				gl.Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height);
				gl.MatrixMode(GL.PROJECTION);
				gl.LoadIdentity();
				//var pml = gl.GetUniformLocation((uint)Program.ID, "projectionmatrix");
				//Matrixf m = Matrixf.Perspective(45f, (float)form.ClientSize.Width / form.ClientSize.Height, 0.1f, 100f);
				//gl.UniformMatrix4fv(pml, 1, false, ref m);
				gluPerspective(45f, (float)form.ClientSize.Width / form.ClientSize.Height, 0.1f, 100f);

				gl.MatrixMode(GL.MODELVIEW);
				gl.LoadIdentity();
			}
			catch (Exception e)
			{ }
		}
	}
}
